package com.self.cloudmall.pms.service.impl;

import com.self.cloudmall.pms.entity.CategoryBrandRelationEntity;
import com.self.cloudmall.pms.service.CategoryBrandRelationService;
import com.self.cloudmall.pms.utils.PageUtils;
import com.self.cloudmall.pms.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.self.cloudmall.pms.mapper.BrandMapper;
import com.self.cloudmall.pms.entity.BrandEntity;
import com.self.cloudmall.pms.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandMapper, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //参数查询
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            queryWrapper.lambda().eq(BrandEntity::getBrandId,key)
                    .or().like(BrandEntity::getName,key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateRelative(BrandEntity brand) {
        //更新分类品牌关联表
        CategoryBrandRelationEntity relationEntity = new CategoryBrandRelationEntity();
        relationEntity.setBrandName(brand.getName());
        categoryBrandRelationService.lambdaUpdate().eq(CategoryBrandRelationEntity::getBrandId,brand.getBrandId())
                .update(relationEntity);
        return this.updateById(brand);
    }

}